package com.its.us.web.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.Map;

/**
 * @className JsonUtil
 * @author huguangjun
 * @date 2020/12/3
 * @desc 9:09
 */
public class JsonUtil {

    private static Gson gson = null;
    private static GsonBuilder gsonBuilder = null;

    public static synchronized Gson getInstanceJson() {
        if (gson == null) {
            gson = new Gson();
        }
        return gson;
    }

    private static synchronized GsonBuilder getInstanceJsonBuilder() {
        if (gsonBuilder == null) {
            gsonBuilder = new GsonBuilder();
        }
        return gsonBuilder;
    }

    /**
     * 将object对象转成json格式字符串
     */
    public static String toJson(Object object) {
        getInstanceJsonBuilder().setPrettyPrinting();
        Gson gson = getInstanceJsonBuilder().create();
        return gson.toJson(object);
    }

    /**
     * 将json串转成对象
     *
     * @param json
     * @return
     */
    public static <T> T fromJson(String json,Class<T> classOfT) {
        return getInstanceJson().fromJson(json, classOfT);
    }

    /**
     * 将json串转成Map
     * @param json
     * @return
     */
    public static Map fromJson(String json){
        return getInstanceJson().fromJson(json,Map.class);
    }

}
